package com.bnz.staticpage.service.impl;

import com.alibaba.fastjson.JSON;
import com.bnz.staticpage.dao.TbGoodsDescRepository;
import com.bnz.staticpage.dao.TbGoodsRepository;
import com.bnz.staticpage.dao.TbItemCatRepository;
import com.bnz.staticpage.dao.TbItemRepository;
import com.bnz.staticpage.entity.TbGoods;
import com.bnz.staticpage.entity.TbGoodsDesc;
import com.bnz.staticpage.entity.TbItem;
import com.bnz.staticpage.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author xy
 * @date 2022/11/23
 */
@Service
public class PageServiceImpl implements PageService {
    @Autowired
    SpringTemplateEngine engine;
    @Autowired
    TbGoodsRepository goodsRepository;
    @Autowired
    TbGoodsDescRepository goodsDescRepository;
    @Autowired
    TbItemCatRepository itemCatRepository;
    @Autowired
    TbItemRepository itemRepository;
    @Override
    public void createHtml(Long id) throws IOException {
        Context context = new Context();
        Map dataMap = new HashMap();

        TbGoods goods = this.goodsRepository.findById(id).orElse(null);
        dataMap.put("goods",goods);

        TbGoodsDesc goodsDesc = goodsDescRepository.findById(id).orElse(null);
        dataMap.put("goodsDesc",goodsDesc);

        String category1Name = itemCatRepository.findById(goods.getCategory1Id()).orElse(null).getName();
        String category2Name = itemCatRepository.findById(goods.getCategory2Id()).orElse(null).getName();
        String category3Name = itemCatRepository.findById(goods.getCategory3Id()).orElse(null).getName();

        dataMap.put("category1Name",category1Name);
        dataMap.put("category2Name",category2Name);
        dataMap.put("category3Name",category3Name);

        dataMap.put("itemImages", JSON.parseArray(goodsDesc.getItemImages(),Map.class));



        dataMap.put("customAttributeItems",JSON.parseArray(goodsDesc.getCustomAttributeItems(),Map.class));
        dataMap.put("specificationItems",JSON.parseArray(goodsDesc.getSpecificationItems(),Map.class));

        List<TbItem> items  = itemRepository.findByGoodsIdOrderByIsDefaultAsc(id);
       dataMap.put("items",items);
       dataMap.put("item",items.get(0));

        System.out.println(dataMap);
        context.setVariables(dataMap);
        Writer writer =  new FileWriter("E:\\SoftWare\\nginx-1.22.1\\html\\"+id+".html");
        engine.process("item",context,writer);
    }
}
